<template>

    <Row class="box-padding organise">
        <Col span="4" class="organise-tree">
            <Tree :data="data1" @on-select-change="treeSelect"></Tree>
        </Col>
        <Col span="20" class="organise-main">
        <div style="margin-bottom:20px;">
            <Button v-if="buttomNum.parentId == '0' && addEntpButton" type="primary" style="margin-right:20px;" @click="addBtn(1)">新增工程公司</Button>
            <Button v-if="buttomNum.parentId == '0' && addAreaButton" type="primary" style="margin-right:20px;" @click="addBtn(2)">新增区域</Button>
            <Button type="primary" @click="addBtn(3)" v-if="isShow && addDeptButton">新增部门</Button>
        </div>
        <Table border :columns="columns1" :data="data2">
            <template slot="action" slot-scope="{ row, index }">
                <Button type="text" size="small" ghost style="margin-right: 5px;" :style="row.canBeEdit ? 'color:#2d8cf0' : 'color:#ccc'" v-if="editButton" @click="editHref(row, 'edit')">编辑</Button>
                <Button type="text" size="small" ghost style="margin-right: 5px;color:#2d8cf0" v-if="detailButton" @click="editHref(row, 'detail')">详情</Button>
                <Button type="text" size="small" ghost :style="row.canBeEdit ? 'color:#2d8cf0' : 'color:#ccc'" v-if="delButton" @click="remove(row,'delete')">删除</Button>
            </template>
        </Table>
        <div class="page-div">
            <Page :total="total" class="tab-page" :page-size="parmes.pageSize" :page-size-opts='[10,20,50,100]' show-sizer show-elevator show-total @on-change="pageChange" @on-page-size-change="onPageSizeChange" />
        </div>
        </Col>
    </Row>

</template>

<script>
import Utils from '../../common/util'
export default {
    name: 'CompanyOrganization',
    data() {
        return {
            isShow: true,
            total: 0,
            parmes: {
                pageSize: 10,
                currentPage: 1,
                whereMap: {
                    parentId: '',
                    types: [1, 4, 5, 8]
                }
            },
            parentId:'',
            data1: [],
            columns1: [{
                    title: '序号',
                    align: 'center',
                    width: '80',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.parmes.currentPage - 1) * this.parmes.pageSize + 1
                        )
                    }
                },
                {
                    title: '名称',
                    align: 'center',
                    render: (h, params) => {
                        return h('span',
                            params.row.shortName ? params.row.shortName : params.row.name
                        )
                    }
                },
                {
                    title: '所属机构',
                    key: 'parentName',
                    align: 'center'
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center'
                }
            ],
            data2: [],
            buttomNum: {},
            treeSelectData: [],
            treeList:[],
            checkTreeEntId:'',
            enterpriseId: '',
            addEntpButton: false, //新增工程公司
            addAreaButton: false, //新增区域
            addDeptButton: false, //新增部门
            editButton: false, //编辑按钮
            detailButton: false, //详情按钮
            delButton: false, //删除按钮
            buttonList: localStorage.getItem('buttonList'), //按钮权限
        }
    },
    created() {
        let userInfo = JSON.parse(localStorage.getItem('userList'))
        this.enterpriseId = userInfo.enterpriseId
        this.treeEnterprise()
    },
    mounted() {
        this.getButtonStatus()
    },
    methods: {
        //获取按钮权限
        getButtonStatus() {
            let path = this.$route.name
            JSON.parse(this.buttonList).forEach((item, index) => {
                if (Object.keys(item)[0] == path) {
                    this.button = item[path];
                }
            })
            this.button.forEach(val => {
                if (val.code == "P_0101_01") {
                    this.addEntpButton = true;
                } else if (val.code == "P_0101_02") {
                    this.addAreaButton = true;
                } else if (val.code == "P_0101_03") {
                    this.addDeptButton = true
                } else if (val.code == "P_0101_04") {
                    this.editButton = true
                } else if (val.code == "P_0101_05") {
                    this.delButton = true
                } else if (val.code == "P_0101_06") {
                    this.detailButton = true
                }
            })
        },
        // 部门新增路由跳转
        addBtn(data) {
            if (this.treeSelectData.length == 0) {
                this.$Message.warning('请先选择公司/区域/部门')
            } else {
                const route = {
                    name: data === 1 ?
                        'company-add' : data === 2 ?
                        'area-add' : 'department-add',
                    params: {
                        type: 'add',
                        id: this.buttomNum.objectId,
                        name: data === 1 ?
                            '新增公司' : data === 2 ?
                            '新增区域' : '新增部门',
                        objectId:'1',
                        parentId:'1',
                        parentName:'1'
                    },
                    query: {
                        parentName: this.buttomNum.shortName ? this.buttomNum.shortName : this.buttomNum.title,
                        type: this.buttomNum.type
                    }
                }
                this.$router.push(route)
            }
        },
        // 1  公司   5  区域    4  8  部门
        // 编辑/详情   跳转
        editHref(item, type) {
            let params = {
                name: type == 'edit' ? '编辑' : '详情',
                type: type == 'edit' ? 'edit' : 'detail',
                id: item.id,
                objectId: item.objectId,
                parentId: item.parentId,
                parentName: item.parentName,

            }
            if (!item.canBeEdit && type == 'edit') {
                return false
            } else {
                if (item.type == 4 || item.type == 8) {
                    this.$router.push({
                        name: type == 'edit' ? 'department-edit' : 'department-detail',
                        params: params
                    })
                } else if (item.type == 1) {
                    this.$router.push({
                        name: type == 'edit' ? 'company-edit' : 'company-detail',
                        params: params
                    })
                } else if (item.type == 5) {
                    this.$router.push({
                        name: type == 'edit' ? 'area-edit' : 'area-detail',
                        params: params
                    })
                }
            }

        },
        // 机构部门树
        treeEnterprise() {
            this.$api.companyOrganization.treeEnterprise().then(resp => {
                if (resp.code == 200) {
                    this.$set(resp.data[0],'expand',true)
                    this.buttomNum = JSON.parse(sessionStorage.getItem('buttomNumObj')) ? JSON.parse(sessionStorage.getItem('buttomNumObj')) : resp.data[0]  // resp.data[0]
                    this.parmes.whereMap.parentId = sessionStorage.getItem('companyId') ? sessionStorage.getItem('companyId') : resp.data[0].objectId
                    this.getOrgTreeList()
                    this.data1 = resp.data;
                    resp.data.forEach(item=>{
                        this.treeList.push(item);
                        if(item.children.length>0){
                            item.children = this.getCheildItem(item.children);
                        }
                    })
                } else {
                    this.$Message.warning(resp.message)
                }
            })
        },
        //递归树状结构
      getCheildItem(data){
            let item = data;
            const arr = [];
            item.forEach(val => {
                this.treeList.push(val);
                let obj = {};
                obj.title = val.title;
                obj.parentId = val.parentId;
                obj.objectId = val.objectId;
                obj.type = val.type;
                obj.children = [];
                obj.expand = true;
                if(val.children.length > 0){
                    obj.children = this.getCheildItem(val.children)
                }
                arr.push(obj);
            })
            return arr
      },
        //循环查询父级
      getParent(id){
        for (var i = 0, length = this.treeList.length; i < length; i++){
          let item = this.treeList[i];
          if(item.objectId == id) {
            if (item.type == 1||item.type == 5) {
              this.checkTreeEntId = item.objectId;
              return
            } else {
              this.getParent(item.parentId);
            }
          }
        }

      },
        // 树上面的点击事件：根据部门id获取table列表
        treeSelect(item) {
            if (item.length) {
                let obj = item[0];
                if (obj && !obj.objectId) {
                    this.isShow = false
                } else if (obj.type == 1 || obj.type == 5) {
                    if (obj.objectId === this.enterpriseId) {
                        this.isShow = true
                    } else {
                        this.isShow = false
                    }
                } else {
                    // this.isShow = this.treeSelect1(obj)
                    //找它的父级,
                    this.checkTreeEntId = '';
                    this.getParent(obj.parentId);
                    if(!this.enterpriseId){
                        this.isShow = false;
                    }else if(this.enterpriseId == this.checkTreeEntId){
                        this.isShow = true;
                    }else{
                        this.isShow = false;
                    }
                }
                

                if (this.treeSelectData[0] && this.treeSelectData[0].id != item[0].id) {
                    this.parmes.currentPage = 1;
                }
            }
            this.treeSelectData = item;
            if (!item[0].objectId && item[0].title === "工程公司") {
                this.$Message.warning('请选择具体的工程公司！')
                return;
            }
            if (!item[0].objectId && item[0].title === "区域指挥部") {
                this.$Message.warning('请选择具体的区域指挥部！')
                return;
            }
            if (item && item.length > 0) {
                sessionStorage.setItem('companyId',item[0].objectId)
                sessionStorage.setItem('buttomNumObj',JSON.stringify(item[0]))
                this.parmes.whereMap.parentId = item[0].objectId
                this.buttomNum = item[0]
            }
            this.getOrgTreeList()
        },
        getOrgTreeList(){
            this.$api.companyOrganization.orgTreeList(this.parmes).then(resp => {
                if (resp.code == 200) {
                    this.data2 = resp.data.resultObject
                    this.total = resp.data.totalRecord
                } else {
                    this.$Message.warning(resp.message)
                }
            })
        },
        // 分页页码变化
        pageChange(index) {
            this.parmes.currentPage = index
            this.getOrgTreeList()
        },
        // 分页页码变化
        onPageSizeChange(size) {
            this.parmes.pageSize = size
            this.getOrgTreeList()
        },
        //删除
        remove(item, type) {
            if (item.canBeEdit) {
                this.$Modal.confirm({
                    title: '温馨提示',
                    closable: true,
                    content: '确认删除吗？',
                    width: 360,
                    onOk: () => {
                        this.getDeleteType(item, type);
                    }
                })
            } else return

        },
        getDeleteType(item, type) {
            if (item.type === 4 || item.type === 8) {
                this.getEnterpriseDeptDetail(item.objectId)
            }
            if (item.type === 1) {
                this.getEnterpriseDetail(item.objectId)
            }
            if (item.type === 5) {
                this.getEnterpriseAreaDetail(item.objectId)
            }
        },
        //获取部门详情
        getEnterpriseDeptDetail(id) {
            this.$api.companyOrganization.deptDetail(id).then(res => {
                if (res.code === 200) {
                    //执行删除操作
                    this.deptDelete(res.data)
                } else {
                    this.$Message.error(res.data.data)
                }
            })
        },
        //获取公司详情
        getEnterpriseDetail(id) {
            this.$api.companyOrganization.getEnterpriseDetail(id).then(res => {
                if (res.code === 200) {
                    this.delEnterprise(res.data)
                } else {
                    this.$Message.error(res.data.data)
                }
            })
        },
        //获取机构(区域)详情
        getEnterpriseAreaDetail(id) {
            this.$api.companyOrganization.enterpriseDetail(id).then(res => {
                if (res.code === 200) {
                    this.areaDelete(res.data)
                } else {
                    this.$Message.error(res.data.data)
                }
            })
        },
        //删除部门
        deptDelete(params) {
            this.$api.companyOrganization.deptDelete(params).then(res => {
                if (res.code === 200) {
                    this.$Message.success('删除成功')
                    this.treeEnterprise()
                    this.$api.companyOrganization.orgTreeList(this.parmes).then(resp => {
                        if (resp.code == 200) {
                            this.data2 = resp.data.resultObject
                            this.total = resp.data.totalRecord
                        } else {
                            this.$Message.warning(resp.message)
                        }
                    })
                } else {
                    this.$Message.error(res.message)
                }
            })
        },
        //删除公司
        delEnterprise(params) {
            this.$api.companyOrganization.delEnterprise(params).then(res => {
                if (res.code === 200) {
                    this.$Message.success('删除成功')
                    this.treeEnterprise()
                    this.$api.companyOrganization.orgTreeList(this.parmes).then(resp => {
                        if (resp.code == 200) {
                            this.data2 = resp.data.resultObject
                            this.total = resp.data.totalRecord
                        } else {
                            this.$Message.warning(resp.message)
                        }
                    })
                } else {
                    this.$Message.error(res.message)
                }
            })
        },
        //删除机构
        areaDelete(params) {
            this.$api.companyOrganization.enterpriseAreaDelete(params).then(res => {
                if (res.code === 200) {
                    this.$Message.success('删除成功')
                    this.treeEnterprise()
                    this.$api.companyOrganization.orgTreeList(this.parmes).then(resp => {
                        if (resp.code == 200) {
                            this.data2 = resp.data.resultObject
                            this.total = resp.data.totalRecord
                        } else {
                            this.$Message.warning(resp.message)
                        }
                    })
                } else {
                    this.$Message.error(res.message)
                }
            })
        }

    }
}
</script>

<style lang="scss">
.box-padding.organise{
    height: calc(100% - 0px);
    .organise-tree {
        padding: 20px;
        height:100%;
        border-right: 1px solid #ebeef1;
        overflow: auto; 
    }
    .organise-main{
        padding:10px;
    }
}

</style>
